package net.atomtree.corrsepond.analyse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by czk on 2016/1/3.
 */
public class JsonAnalyse {
    /**
     * give a restResult,covert a json object by json array index and alone mode can return a json object
     * @param restResult
     * @param JSONArrayIndex
     * @return
     * @throws Exception
     */
    public JSONObject alone(String restResult,int JSONArrayIndex) throws Exception {
        if (restResult.equals(""))
            throw new Exception("restResult value is null");
        JSONArray array=JSONArray.fromObject(restResult);
        Object json=array.get(JSONArrayIndex);
        if(null==json){
            throw new  Exception("json array analyse error may array is null or index error");
        }
        return (JSONObject)json ;
    }

    /**
     * give a restResult,covert a json array  and multiple mode can return a json list by json array size
     * @param restResult
     * @return
     * @throws Exception
     */
    public List<JSONObject> multiple(String restResult) throws Exception {
        if (restResult.equals(""))
            throw new Exception("restResult value is null");
        JSONArray array=JSONArray.fromObject(restResult);
        int length=array.size();
        List<JSONObject> container=new ArrayList<JSONObject>();
        int initJsonArrayIndex=0;
        for(int jsonArrayIndex=initJsonArrayIndex;jsonArrayIndex<length;jsonArrayIndex++){
            Object jsonArrayObject=array.get(jsonArrayIndex);
            if (null!=jsonArrayObject) {
                JSONObject json = JSONObject.fromObject(jsonArrayObject);
                container.add(json);
            }
        }
        return container;
    }
}
